package fregat.base.util;

import java.util.Timer;
import java.util.TimerTask;

/**
 * This class wraps a standard timer (java.util.Timer) to be started and stopped
 * more easier.
 *
 * @author Alexander Mann <br><b><i>ECO_L O G</i> &nbsp Logistiksysteme GmbH</b>
 * @version 1.0
 */
public abstract class Timeout {
  private Timer timer; // timer thread
  private long timeout; // timeout in [ms]
  private String name; // name of timer

  /**
   * Creates a new timer with the specified timeout.
   *
   * @param timeout Timeout in [ms]
   */
  public Timeout(long timeout) {
    this(timeout, "Timeout");
  }

  public Timeout(long timeout, String name) {
    this.timeout = timeout;
    this.name = name;
  }

  /**
   * This method will be called if timeout is reached.
   */
  protected abstract void timeout();

  /**
   * Start the timer.
   */
  public void start() {
    stop();

    timer = new Timer();

    timer.schedule(new TimerTask() {
      public void run() {
        timeout();
      }
    }, timeout);
  }

  /**
   * Stop the timer.
   */
  public void stop() {
    if (timer != null) {
      timer.cancel();
    }
  }

  public String getName() {
    return name;
  }
}
